/**
 * 2016年11月18日
 */
package jdk;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class MainSub50 {
	static volatile boolean isSubRun = true;
	static ReentrantLock lock = new ReentrantLock();
	static Condition subWait = lock.newCondition();
	static Condition mainWait = lock.newCondition(); 
	public static void main(String[] args) throws InterruptedException {
		Runnable sub = ()->{
		int times = 50;
			while(times>0){
				lock.lock();
				try{
					while(!isSubRun){
							subWait.await();
					}
					System.out.println("Sub 第 "+(50-times+1)+" 次");
					for(int i = 0;i<10;i++){
						System.out.print("sub "+i+" ");
					}
					System.out.println();
					isSubRun = false;
				}catch(Exception e){
					e.printStackTrace();
				}finally{
					mainWait.signalAll();
					lock.unlock();
				}
				times --;
			}
		};
		new Thread(sub).start();
		main();	
	}
	static void main() throws InterruptedException{
		int times = 50;
		while(times>0){
			try{
				lock.lock();
				while(isSubRun){
					mainWait.await();
				}
				System.out.println("main 第 "+(50-times+1)+" 次");
				for(int i =0;i<10;i++){
					System.out.print("main "+i+" ");
				}
				System.out.println();
				isSubRun = true;
			}catch(Exception e){
				e.printStackTrace();
			}finally{
				subWait.signalAll();
				lock.unlock();
			}
			times -- ;
		}
	}
}
